//
//  VVYCityViewCellModel.m
//  viviyoo
//
//  Created by viviyoo on 15/11/10.
//  Copyright © 2015年 viviyoo. All rights reserved.
//

#import "VVYCityViewCellModel.h"


@interface VVYCityViewCellModel ()

@property (nonatomic, strong, readwrite) NSArray *citys;

@property (nonatomic, assign, readwrite) CGFloat viewHeight;

@property (nonatomic, assign, readwrite) NSUInteger maxComponents;

@end


@implementation VVYCityViewCellModel


MJExtensionCodingImplementation

/**
 *  初始化
 */
+ (instancetype)cityGroupsModelWithCitys:(NSArray *)citys andMaxCount:(NSUInteger)maxCount{

    VVYCityViewCellModel *model = [[VVYCityViewCellModel alloc] init];
    model.citys = citys;
    model.maxComponents = maxCount;
    return model;
}

- (void)setCitys:(NSArray *)citys{

    _citys = citys;
    
    [self setUpviewHeight];
}

- (void)setMaxComponents:(NSUInteger)maxComponents{
    
    _maxComponents = maxComponents;

    if (_citys.count > _maxComponents) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:_citys];
        for (NSUInteger i = self.maxComponents; i < array.count; i++) {
            [array removeObjectAtIndex:i];
        }
        self.citys = [array copy];
    }
}

/**
 *  计算cellHeight
 */
- (void)setUpviewHeight{
    
    //NSlog(@"%zd",self.citys.count);
      NSUInteger row = (self.citys.count + CityViewCityBtnCount - 1) / CityViewCityBtnCount;
     _viewHeight = row  * (CityViewBtnHeight + CityViewBtnMargin) + CityViewBtnMargin;
    
}

/**
 *  增加城市
 */
- (void)addCity:(NSString *)city{
    
    BOOL exit = NO;
    NSUInteger index = 0;
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.citys];
    
    //有重复的先干掉
    for (NSString *oldCity in array) {
        if ([oldCity isEqualToString:city]) {
            exit = YES;
            index = [array indexOfObject:oldCity];
        }
    }
    //如果已经存在，交换位置
    if (exit) {
        
        [array removeObjectAtIndex:index];
        [array insertObject:city atIndex:0];
        
    }else{
    
        if(array > 0){
            
            [array insertObject:city atIndex:0];
            
        }else{
            
            [array addObject:city];
        }
        
    }
    
 
    
    //如果大于8个城市就去掉最后一个
    if (array.count > self.maxComponents) {
        [array removeLastObject];
    }
    
    self.citys = [array copy];

}

@end
